<template>
    <el-dialog title="打开数据库" :visible.sync="showDbList" :close-on-click-modal="false" width="300px">
      <div class="connect_list">
        <el-tree
          class="filter-tree"
          :data="dbList"
          :props="defaultProps"
          @node-click="connectDb"
          default-expand-all
          ref="dbTree">
          <template slot-scope="{ node }">
            <div><i class="el-icon-coin db_tree_icon"></i>{{ node.label }}</div>
          </template>
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDbList = false" size="mini">取消</el-button>
      </div>
    </el-dialog>
</template>

<script>
import { connect_db } from "@/api/mysql";

export default {
    name: 'ConnectDb',
    // props: ['showDbList', 'databases', 'currentDbIndex', 'editTabs', 'dbList'],
    props: {
        showDbList: false,
        databases: [],
        currentDbIndex: '0',
        editTabs: [],
        dbList: []
    },
    methods: {
        connectDb(data) {
        // this.$emit('connectDb', data);
        this.create_db_connection(data.label);
        this.showDbList = false;
        },
        create_db_connection(database) {
            var self = this;
            let conf = {};
            for (let i = 0; i < this.serverList.length; i++) {
                if (this.serverList[i].label === this.currentServerName) {
                conf = this.serverList[i];
                break;
                }
            }
            connect_db(conf.host, conf.port, conf.user, conf.password, database).then(res => {
                let tables = [];
                for (let i = 0; i < res.length; i++) {
                tables.push({
                    id: i,
                    name: res[i]
                });
                }
                self.databases.push({ 
                    name: database,
                    lastTabsValue: '1',
                    tables: tables,
                    tableFilter: tables,
                    tab: []
                });
                self.currentDbIndex = (self.databases.length - 1) + '';
                self.editTabs = [];
            }, (err) => {
                this.$message.error(err);
            });
        },
    },
}
</script>